package net.atomtree.service;

import net.atomtree.handler.APPHandler;
import net.atomtree.handler.JobHandler;
import net.atomtree.handler.RestHandler;
import net.atomtree.handler.StageHandler;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class IndexService1 {
		public static int priorShuffleReadRecords=0;
		public static int priorNumCompleteTasks=0;
		private static final Logger logger = LoggerFactory.getLogger(IndexService1.class);
		//	StringBuffer url=new StringBuffer();
		//	url.append("http://101.204.243.107:4040/api/v1");
		public JSONObject countSpeed (StringBuffer url) throws Exception{
			String URL=url.toString();
			StringBuffer appUrl=new StringBuffer(url.toString());
			StringBuffer jobUrl=new StringBuffer(url.toString());
			StringBuffer stageUrl=new StringBuffer(url.toString());
			String appName=getAppName(appUrl);
			String stageArrLength=getStageArrLength(jobUrl,appName);
			StageHandler stageHandler=new StageHandler();
			JSONObject stageJson=getStageJson(stageHandler,stageUrl,appName);
			stageJson=count(stageJson,stageArrLength,stageHandler,URL,appName);
			return stageJson;
		}

	public static String getAppName(StringBuffer appUrl)throws Exception{
		String JsonArr=RestHandler.getApplication(appUrl);
		APPHandler appHandler=new APPHandler();
		String appName=appHandler.getAppNameByString(JsonArr);
		if(null==appName||appName.equals(null)){
			System.out.println("appName解析失败name为null");
			throw new Exception("appName 为null" );
		}
		appName=appName.replace(" ", "%20");
		return appName;
	}

	public static String getStageArrLength(StringBuffer jobUrl,String appName) throws Exception{
		String jobArr= RestHandler.getApplicationJob(jobUrl, appName);
		if(null==jobArr||jobArr.equals(" "))
			throw new Exception("jobArr为null");
		JobHandler job=new JobHandler();
		JSONObject jobJson=job.getJob(jobArr);
		String stages=jobJson.get("stageIds").toString();
		String stageArrLength=stages.substring(stages.lastIndexOf("[")+1, stages.lastIndexOf("]"));
		if(stageArrLength.length()>2){
			stageArrLength=stageArrLength.substring(stageArrLength.indexOf(","));
		}
		return stageArrLength;
	}
	public static JSONObject getStageJson(StageHandler stageHandler,StringBuffer stageUrl,String appName)throws Exception{
		String stageArr= RestHandler.getApplicationStages(stageUrl, appName);
		stageHandler=new StageHandler();
		JSONObject stageJson=stageHandler.getStage(stageArr);
		return  stageJson;
	}

	public JSONObject count(JSONObject stageJson,String stageArrLength,StageHandler stageHandler,String URL,String appName)throws Exception{
		if(null!=stageJson) {
			//根据stages数组的长度建立存放时间的数组
			int stageArrlength = Integer.parseInt(stageArrLength);
			if (stageArrlength == 0) {
				//如果只有一个stage启动单个stage模式（计算task数量当做处理数据的记录数）
				stageJson=singleModule(stageJson);
				return stageJson;
			}
				//有多个stage，则需要将多个stage的时间进行统计
				stageJson=multiModule(stageJson,stageArrlength,stageHandler,URL,appName);
				return stageJson;
			}
		return null;
	}

	public JSONObject singleModule(JSONObject stageJson){
		//迭代运算只有一个stage，需要统计task任务的数量来计算执行数据的处理条数
		//stages rest的numCompleteTasks
		int nowNumCompleteTasks = Integer.parseInt(stageJson.get("numCompleteTasks").toString());
		stageJson.element("shuffleReadRecords", nowNumCompleteTasks - priorNumCompleteTasks);
		priorNumCompleteTasks = nowNumCompleteTasks;
		logger.debug("priorNumCompleteTasks:" + priorNumCompleteTasks);
		return stageJson;
	}
	public JSONObject multiModule(JSONObject stageJson,int stageArrlength,StageHandler stageHandler,String URL,String appName)throws  Exception{
		int runTimeSum=analyseRumTime(stageArrlength,stageHandler,URL,appName);
		//将executeRunTime的值放进 stage Rest不带id的json对象中
		stageJson.element("executorRunTime", runTimeSum);
		return stageJson;
	}

	public int analyseRumTime(int stageArrlength,StageHandler stageHandler,String URL,String appName) throws Exception{
		//有多个stage，则需要将多个stage的时间进行统计
		int executeRunTimeSum[] = new int[stageArrlength + 1];
		for (int i = 0; i <= stageArrlength; i++) {
			String stageArrById = RestHandler.getApplicationStagesByAppappnameAndStageappname(new StringBuffer(URL), appName, new Integer(i).toString());
			//得到的从小到大的stageId的stageArr,循环的转换成json对象，读取json对象的executeRunTime
			JSONObject stageObjectById = stageHandler.getStage(stageArrById);
			int stageId = Integer.parseInt(stageObjectById.get("stageId").toString());
			int rumTime = Integer.parseInt(stageObjectById.get("executorRunTime").toString());
			//根据stageId当做数组下标，存放executeRunTime
			executeRunTimeSum[stageId] = rumTime;
		}
		int runTimeSum = 0;
		for (int i = 0; i < executeRunTimeSum.length; i++) {
			runTimeSum += executeRunTimeSum[i];
		}
		return runTimeSum;
	}
}
